package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service
@Slf4j
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UserDao userDao;

    @Override
    public List<Menu> findByUsername(String username) {
        //根据用户名查询用户信息,根据表关系获取用户信息的角色信息
        Set<Role> roles = userDao.findByUsername(username).getRoles();
        //将菜单信息封装到list集合中
        List<Menu> List = new ArrayList<Menu>();
        for (Role role : roles) {
            //将数据库中用户信息封装到menus中
            List<Menu> menus = menuDao.findMenuByRoleId(role.getId());
            //遍历获取菜单中信息
            for (Menu menu : menus) {
                if (menu.getParentMenuId() == null){
                    //根据父菜单Id查询子菜单返回集合
                    List<Menu> children = menuDao.findByParentId(menu.getId());
                    //把查询到的子菜单集合添加到父菜单
                    menu.setChildren(children);
                    List.add(menu);
                }
            }
        }
        //定义集合,接收父菜单
        Map<Integer,Menu> parentMap = new HashMap<>();
        List<Integer> parentPriority = new ArrayList<>();

        //遍历菜单集合
        for (Menu menu : List) {
            //调用子菜单排序方法获取集合赋值给父菜单
            menu.setChildren(getChildPriority(menu));
            parentPriority.add(menu.getPriority());
            parentMap.put(menu.getPriority(),menu);
        }
        Collections.sort(parentPriority);
        //根据优先级添加到菜单集合中
        List=new ArrayList<>();
        for (Integer integer : parentPriority) {
            List.add(parentMap.get(integer));
        }
        return List;
    }

    //获取子菜单优先级排序方法
    private List<Menu> getChildPriority(Menu menu){
        Map<Integer,Menu> childMenu = new HashMap<>();
        List<Integer> childPriority = new ArrayList<>();

        for (Menu menu1 : menu.getChildren()) {
            childMenu.put(menu1.getPriority(),menu1);
            childPriority.add(menu1.getPriority());
        }
        Collections.sort(childPriority);
        List<Menu> childMenuList = new ArrayList<Menu>();
        for (Integer integer : childPriority) {
            childMenuList.add(childMenu.get(integer));
        }
        return childMenuList;
    }
}
